﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomerService
{
    public partial class SequenceTab : System.Web.UI.UserControl
    {
        private SalesManagerEntities _context;
        private tblCustomer _customer;
        private tblSequenceStep[][] _stepArray;
        private tblSequenceOrder[] _sequenceOrderList;
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                foreach (RepeaterItem item1 in repeater1.Items)
                {
                    foreach (RepeaterItem item2 in ((Repeater)item1.FindControl("repeater2")).Items)
                    {
                        HiddenField txtSequenceStepID = (HiddenField)item2.FindControl("txtSequenceStepID");
                        TextBox txtSequenceDelay = (TextBox)item2.FindControl("txtSequenceDelay");
                        TextBox txtSequenceTerm = (TextBox)item2.FindControl("txtSequenceTerm");
                        int sequenceStepID = int.Parse(txtSequenceStepID.Value);

                        tblSequenceStep sequenceStep = (tblSequenceStep)_context.GetObjectByKey(
                            new System.Data.EntityKey("SalesManagerEntities.tblSequenceStep", "SequenceStepID", sequenceStepID));
                        short delay = sequenceStep.Delay;
                        short.TryParse(txtSequenceDelay.Text, out delay);
                        sequenceStep.Delay = delay;
                        short term = sequenceStep.RecurrenceTerm;
                        short.TryParse(txtSequenceTerm.Text, out term);
                        sequenceStep.RecurrenceTerm = term;

                        foreach (RepeaterItem item3 in ((Repeater)item2.FindControl("repeater3")).Items)
                        {
                            HiddenField txtSequenceStepProductID = (HiddenField)item3.FindControl("txtSequenceStepProductID");
                            TextBox txtSequenceProductPrice = (TextBox)item3.FindControl("txtSequenceProductPrice");
                            int sequenceStepProductID = int.Parse(txtSequenceStepProductID.Value);

                            tblSequenceStepProduct sequenceStepProduct = (tblSequenceStepProduct)_context.GetObjectByKey(
                                new System.Data.EntityKey("SalesManagerEntities.tblSequenceStepProduct", "SequenceStepProductID", sequenceStepProductID));
                            decimal price;
                            if (sequenceStepProduct.Price != null)
                                price = (decimal)sequenceStepProduct.Price;
                            decimal.TryParse(txtSequenceProductPrice.Text, out price);
                            sequenceStepProduct.Price = price;
                        }
                    }
                }
            }
        }

        public new void Load(SalesManagerEntities context, tblCustomer customer)
        {
            _context = context;
            _customer = customer;
            _sequenceOrderList = _customer.cachedSequenceOrders.OrderBy(o=>o.SequenceOrderID).ToArray();
            if (!IsPostBack)
            {
                lvSequenceList.DataSource = _sequenceOrderList;
                lvSequenceList.DataBind();
            }
            if (_sequenceOrderList.Count() > 0 && lvSequenceList.SelectedIndex < 0)
                lvSequenceList.SelectedIndex = 0;
            if ( !IsPostBack )
                SetSteps(false);
        }

        protected void SequenceListSelectedIndexChanging(object sender, ListViewSelectEventArgs e)
        {
            lvSequenceList.SelectedIndex = e.NewSelectedIndex;
            lvSequenceList.DataSource = _sequenceOrderList;
            lvSequenceList.DataBind();
            SetSteps(true);
        }

        public void SetSteps(bool forceUpdate)
        {
            if (lvSequenceList.SelectedIndex >= 0)
            {
                tblSequenceOrder sequenceOrder = _sequenceOrderList[lvSequenceList.SelectedIndex];

                List<SequenceStepPosition> steps = new List<SequenceStepPosition>();

                AddSteps(steps, _customer.cachedSequenceSteps.Where(c => c.SequenceOrder == sequenceOrder && c.PrevStep == null), 0);

                // Count the rows and columns required
                int rowCount = 1;
                int lastLevel = 0;
                int colCount = 1;
                foreach (SequenceStepPosition ssp in steps)
                {
                    if (ssp.Position + 1 > colCount)
                        colCount = ssp.Position + 1;
                    if (ssp.Position < lastLevel)
                        rowCount++;
                    lastLevel = ssp.Position;
                }

                // Allocate an array for the rows
                _stepArray = new tblSequenceStep[rowCount][];
                for (int i = 0; i < rowCount; i++)
                    _stepArray[i] = new tblSequenceStep[colCount];
                lastLevel = 0;
                rowCount = 0;
                foreach (SequenceStepPosition ssp in steps)
                {
                    if (ssp.Position < lastLevel)
                        rowCount++;
                    lastLevel = ssp.Position;
                    _stepArray[rowCount][ssp.Position] = ssp.SequenceStep;
                }

                repeater1.DataSource = _stepArray;
                repeater1.DataBind();

                btnCancel.Enabled = (sequenceOrder.SequenceStatusCode == "I" || sequenceOrder.SequenceStatusCode == "A");
            }
            else
                btnCancel.Enabled = false;
        }

        private void AddSteps( List<SequenceStepPosition> stepList,
            IEnumerable<tblSequenceStep> steps,
            int level)
        {
            foreach (tblSequenceStep step in steps)
            {
                stepList.Add(new SequenceStepPosition(step, level));
                AddSteps(stepList, step.SequenceOrder.OrderHeader.Customer.cachedSequenceSteps.Where(t=>t.PrevStep == step), level + 1);
            }
        }

        protected void brnCancel_Click(object sender, EventArgs e)
        {
        }
    }

    class SequenceStepPosition
    {
        public tblSequenceStep SequenceStep;
        public int Position;

        public SequenceStepPosition( tblSequenceStep _step, int _position )
        {
            SequenceStep = _step;
            Position = _position;

        }
    }
}